package view.views;

import globalOperations.MarkupMethods;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.part.ViewPart;

import run.Activator;
import singleton.Singleton;
import view.listener.KeyListener;
import controller.UseCaseController;
import controller.data.EditDocumentationRevision;
import controller.data.ReadDocumentationRevision;
import controller.data.searchRevision.SearchRevisionRequest;
import controller.data.searchRevision.SearchRevisionResponse;

public class RevisionView extends ViewPart implements ISelectionListener {

	private Text textSearch;
	FormToolkit toolkitRev;
	ScrolledForm formRev;

	/**
	 * The constructor.
	 */
	public RevisionView() {
		IWorkbenchPartSite site = getSite();
	}

	Listener buttonListener = new Listener() {
		Singleton singleton = Singleton.getInstance();
		UseCaseController useCaseControllerImplementation = singleton
				.getUseCaseController();

		public void handleEvent(Event event) {
			Button button = (Button) event.widget;
			if (button.getText().compareTo("search") == 0) {
				Singleton.getInstance().setGetGoForIt(true);
				List<String> listOfTags = getListOfTags();
				SearchRevisionRequest request = new SearchRevisionRequest(
						listOfTags);
				List<SearchRevisionResponse> listOfRevisions = useCaseControllerImplementation
						.searchRevision(request);
				// + Arrays.toString(listOfRevisions.toArray()));
				singleton.setListOfRevisions(listOfRevisions);
				relaodRevision();
				// createViewOfRevisions();
			}
		}
	};

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	@Override
	public void createPartControl(Composite parent) {
		getSite().getWorkbenchWindow().getSelectionService()
				.addPostSelectionListener(this);
		getSite().getWorkbenchWindow().getSelectionService()
				.addSelectionListener(this);
		
		// Close all open editors

		IEditorReference[] editors = getSite().getPage().getEditorReferences();
		IEditorReference[] ref = new IEditorReference[2];
		for (int i = 0; i < editors.length; i++) {
			String tmp01 = editors[i].getName();
			if (tmp01.compareTo("muster.min") == 0) {
				ref[0] = editors[i];
			}
			if (tmp01.compareTo("muster.mene") == 0) {
				ref[1] = editors[i];
			}
		}
		if (ref[0] != null && ref[1] != null)
			getSite().getPage().closeEditors(ref, false);
		else if (ref[0] != null) {
			IEditorReference[] refdel = new IEditorReference[1];
			refdel[0] = ref[0];
			getSite().getPage().closeEditors(refdel, false);
		} else if (ref[1] != null) {
			IEditorReference[] refdel = new IEditorReference[1];
			refdel[0] = ref[1];
			getSite().getPage().closeEditors(refdel, false);
		}

		toolkitRev = new FormToolkit(parent.getDisplay());
		formRev = toolkitRev.createScrolledForm(parent);

		GridLayout gL = new GridLayout();
		gL.numColumns = 1;

		formRev.getBody().setLayout(gL);

		createViewOfRevisions();
	}

	@Override
	public void setFocus() {
		formRev.setFocus();
	}

	private void createViewOfRevisions() {
		createHeader();
		if (Singleton.getInstance().getListOfRevisions().size() != 0) {
			if (Singleton.getInstance().getListOfRevisions() != null
					&& Singleton.getInstance().getListOfRevisions().isEmpty() == false) {
				createResponse();
			}
		} else {
			if (Singleton.getInstance().getGoForIt) {
				Section sectionAnswer = toolkitRev.createSection(formRev
						.getBody(), ExpandableComposite.COMPACT);
				sectionAnswer.setText("Nothing in Database");
				sectionAnswer.setForeground(new Color(null, 255, 0, 0));
			}

		}
	}

	private void createHeader() {

		Section sectionHeader = toolkitRev.createSection(formRev.getBody(),
				Section.DESCRIPTION | ExpandableComposite.TITLE_BAR
						| ExpandableComposite.EXPANDED);
		sectionHeader.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		sectionHeader.setText("Search");
		sectionHeader
				.setDescription("Enter your search tags & seperate them with ';'");
		Composite clientHeader = toolkitRev.createComposite(sectionHeader);
		GridLayout glHeader = new GridLayout();
		glHeader.numColumns = 2;
		clientHeader.setLayout(glHeader);

		textSearch = new Text(clientHeader, SWT.BORDER);
		textSearch.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		textSearch.addKeyListener(new KeyListener(getSite(), this));

		Button buttonSearch = new Button(clientHeader, SWT.PUSH);
		buttonSearch.setText("search");
		buttonSearch.addListener(SWT.Selection, buttonListener);
		buttonSearch.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));

		sectionHeader.setClient(clientHeader);
	}

	private void createResponse() {
		List<SearchRevisionResponse> listOfRevisions = Singleton.getInstance()
				.getListOfRevisions();
		for (int i = 0; i < listOfRevisions.size(); i++) {
			createRevisionSection(listOfRevisions.get(i));
		}
	}
	
	/**
	 * Disposes the toolkit
	 */
	@Override
	public void dispose() {
		formRev.dispose();
		getSite().getWorkbenchWindow().getSelectionService()
				.removeSelectionListener(this);
		super.dispose();
	}

	private void createRevisionSection(
			SearchRevisionResponse searchRevisionResponse) {
		Long defaultRevision = searchRevisionResponse.getDefaultRevision();
		List<ReadDocumentationRevision> allRevisions = searchRevisionResponse.getRevisions();
		for (int i = allRevisions.size() - 1; i >= 0; i--) {
			ReadDocumentationRevision revision = allRevisions.get(i);
			Section sectionRevision = toolkitRev.createSection(formRev.getBody(),
					 Section.TITLE_BAR | ExpandableComposite.TWISTIE);
			sectionRevision.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
			String header = "\""+revision.getHeader()+"\" in ";
			header += " "+searchRevisionResponse.getCategory() + ". Last Change ";
			header += revision.getDate() + " ";
			if (i == defaultRevision) {
				header += " (default)";
			}
			sectionRevision.setText(header);

			Composite compositeRevision = toolkitRev
					.createComposite(sectionRevision);

			GridLayout gL = new GridLayout();
			gL.numColumns = 1;

			compositeRevision.setLayout(gL);

			Browser browserRevision = new Browser(compositeRevision, SWT.NONE);
			browserRevision.setLayoutData(new GridData(GridData.FILL_BOTH));
			browserRevision.setText(MarkupMethods.parseMarkUpToHTML(revision
					.getContent()));

			sectionRevision.setClient(compositeRevision);
		}

	}

	public void selectionChanged(IWorkbenchPart part, ISelection selection) {
	}

	public void relaodRevision() {
		IViewPart view = getSite().getPage().findView(
				"plug_inv01.views.RevisionView");
		getSite().getPage().hideView(view);
		try {
			getSite().getPage().showView("plug_inv01.views.RevisionView");
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}

	public List<String> getListOfTags() {
		String[] tmp = textSearch.getText().split(";");
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < tmp.length; i++) {
			list.add(tmp[i]);
		}
		return list;
	}
}